import 'package:cached_network_image/cached_network_image.dart';
import 'package:collection/collection.dart' show IterableExtension;
import 'package:family_expense/features/account_user/services/role_service.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_core/my_flutter_core.dart';

class UserShared {
  /// Builds the user role chips.
  static List<Widget> buildUserdRoleChips(User user) {
    return user.fullRoles!
        .map((p) => InputChip(
              padding: const EdgeInsets.all(0.0),
              label: Text(
                p.title!,
              ),
              backgroundColor: Colors.blue[200],
              onPressed: () {},
            ))
        .toList();
  }
}

class UserAvatorView extends StatelessWidget {
  const UserAvatorView(this.user, {super.key});

  final User user;

  @override
  Widget build(BuildContext context) {
    return ClipOval(
      child: AspectRatio(
        aspectRatio: 1.0,
        child: CachedNetworkImage(
          imageUrl: user.avatarUrl!,
          fit: BoxFit.cover,
        ),
      ),
    );
  }
}

/// Gets the [Chip] based on [user.enabled].
class UserEnableChip extends StatelessWidget {
  const UserEnableChip(this.enabled, {super.key});

  final bool enabled;

  @override
  Widget build(BuildContext context) {
    return enabled
        ? const Chip(
            padding: EdgeInsets.all(0.0),
            label: Text('正常'),
            backgroundColor: Colors.lightGreenAccent,
          )
        : const Chip(
            padding: EdgeInsets.all(0.0),
            label: Text('禁用'),
            backgroundColor: Colors.orange,
          );
  }
}

class AccountGroupUserRoleSelection extends StatefulWidget {
  const AccountGroupUserRoleSelection(this.selectedRoles, this.onRoleChanged,
      {super.key});

  final List<Role> selectedRoles;
  final ValueChanged onRoleChanged;

  @override
  State<AccountGroupUserRoleSelection> createState() =>
      _AccountGroupUserRoleSelectionState();
}

class _AccountGroupUserRoleSelectionState
    extends State<AccountGroupUserRoleSelection> {
  List<Role> _allRoles = [];
  List<Role> _selectedRoles = [];

  @override
  void initState() {
    super.initState();

    _queryNonSystemLevelRoles();
  }

  @override
  Widget build(BuildContext context) {
    if (_allRoles.isEmpty) {
      return const MyPageTopCenterLoadingIndicator();
    }

    return Column(
      children: _buildAllRoleTiles(),
    );
  }

  List<Widget> _buildAllRoleTiles() {
    return _allRoles.map((p) {
      final selected =
          _selectedRoles.firstWhereOrNull((role) => role.id == p.id) != null;

      return CheckboxListTile(
        title: Text(p.title!),
        subtitle: Text(p.description!),
        value: selected,
        onChanged: (value) {
          selected
              ? _selectedRoles.removeWhere((role) => role.id == p.id)
              : _selectedRoles.add(p);

          widget.onRoleChanged(_selectedRoles);
        },
      );
    }).toList();
  }

  Future<void> _queryNonSystemLevelRoles() async {
    final res = await RoleService().queryNonSystemLevelRoles();

    if (widget.selectedRoles.isNotEmpty) {
      _selectedRoles = widget.selectedRoles.map((p) => p.clone()).toList();
    } else {
      _selectedRoles =
          res.where((p) => p.authority == UserRole.accountGroupUser).toList();
    }

    if (mounted) {
      setState(() => _allRoles = res);
    }

    widget.onRoleChanged(_selectedRoles);
  }
}
